var http = require('http');
var reproxy = require('../index.js');
var Adapter = reproxy.Adapter;
var Proxy = reproxy.Proxy;

/**
 * Creates the adapter
 */
var ArrayAdapter = Object.create(reproxy.Adapter);

/**
 * Initializes the adapter
 */
ArrayAdapter.prototype.init = function () {
    console.log("Initializing adapter");
};

/**
 * Fetches adapter contents
 */
ArrayAdapter.prototype.fetch = function() {
    console.log("Fetching adapter contents...");
    return {
        "app1.vcap.me" : {
            host: 'app1.vcap.me',
            port: 3000
        },
        "app2.vcap.me" : {
            host: 'app2.vcap.me',
            port: 3001
        },
        "app3.vcap.me" : {
            host: 'app3.vcap.me',
            port: 3002
        }
    };
};

/**
 * Test "applications"
 */

var app1 = http.createServer(function(request, response) {
    response.writeHead(200, { 'Content-Type': 'text/plain' } );
    response.write("Hello from application 1\n");
    response.write(new Array(502).join('a'))
    response.end();
}).listen(3000);

var app2 = http.createServer(function(request, response) {
    response.writeHead(200, { 'Content-Type': 'text/plain' } );
    response.write("Hello from application 2");
    response.end();
}).listen(3001);

var app3 = http.createServer(function(request, response) {
    response.writeHead(200, { 'Content-Type': 'text/plain' } );
    response.write("Hello from application 3");
    response.end();
}).listen(3002);

/**
 * Creates the proxy instance
 * @type {Proxy}
 */
var proxy = new reproxy.Proxy(new Adapter());

/**
 * Errors
 */
proxy.on('error', function(request, response, websocket) {
    response.writeHead(500);
    response.write("The requested route is missing.");
});

proxy.on('bandwidth', function(host, request, response) {
    console.log('Request to', host, 'consumed', request, 'b/in &', response, 'b/out')
});

/**
 * Listens at the specified port
 */
proxy.run(80);